// header
let heads = []
// body
let columnData = []

/**
 * add column
 * @param {String} name
 */
function addRow() {
    let column = []
    heads.map(_ => {
        column.push('')
    })
    columnData.push(column)
    updateColumn()
    updateRow()
}

function addColumn(name) {
    heads.push(name)
    let columnCopy = []
    columnData.map(col => {
        col.push('_')
        columnCopy.push(col)
    })
    columnData = columnCopy
    updateColumn()
    updateRow()
}

function updateColumn() {
    $("#fileTableColumn").html('')
    $("#fileTableColumn").append('<th>' +
        '点击红色按钮删除行或列' +
        '</th>>')
    for (let i = 0; i < heads.length; i++) {
        const item = heads[i];
        $("#fileTableColumn").append(`
<th class="text-center" index="${i}">
<div onclick="removeColumn(${i})" class="dot mr-1 bg-red" style="cursor: pointer;display: inline-block"></div>
${item}
</th>`)
    }
}

function updateRow() {
    $("#fileTableRow").html('')
    for (let i = 0; i < columnData.length; i++) {
        let tr = $(`<tr index="${i}"></tr>`)
        tr.append(
            $(`<div onclick="removeRow(${i})" class="dot mr-1 bg-red" style="margin-top: 25px;cursor: pointer;display: inline-block"></div>`)
        )
        for (let index = 0; index < columnData[i].length; index++) {
            const item = columnData[i][index];
            tr.append(`<td index="${index}"><input onchange="dataRowChange(this)" type="text" class="dataRow form-control" value="${item}"></td>`)
        }
        $("#fileTableRow").append(tr)
    }
}

/**
 * 删除一列
 * @param index
 */
function removeColumn(index) {
    heads.splice(index, 1)
    let copycd = columnData
    for (let i = 0; i < copycd.length; i++) {
        columnData[i].splice(index, 1)
    }
    updateColumn()
    updateRow()
}

/**
 * 删除一行
 * @param index
 */
function removeRow(index) {
    columnData.splice(index, 1)
    updateColumn()
    updateRow()
}


function dataRowChange(e) {
    let td = $(e).parent('td')
    let tr = $(td).parent('tr')
    columnData[$(tr).attr('index')][$(td).attr('index')] = e.value
}

function getQueryVariable(variable) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair[0] == variable) {
            return pair[1];
        }
    }
    return (false);
}

$(function () {
    console.clear()
    console.log('Let`s go motherfuck->https://cacode.ren')
    $.ajax({
        type: "GET",
        url: window.location.href + '&json=True',
        dataType: "json",
        async: false,
        success: function (response) {
            columnData = response.data.data
            heads = response.data.head
        },
        error: function (e) {
            if (e.statusText == "timeout") {
                alert("请求超时")
            }
        },
        complete: function () {
        },
    })
    console.log(heads);
    console.log(columnData);
    updateColumn()
    updateRow()


    $('#addColumn').click(() => {
        addColumn($('#columnName').val())
    })

    $('#addRow').click(() => {
        addRow()
    })

    $('#toSubmit').click(() => {
        $.ajax({
            type: "POST",
            url: window.location.pathname + 'Update',
            dataType: "json",
            traditional: true,
            data: {
                filename: getQueryVariable('filename'),
                head: JSON.stringify(heads),
                columns: JSON.stringify(columnData)
            },
            async: false,
            success: function (response) {
                $('#InfoText').css('color', '#28a745')
                $('#InfoText').text(response.data.status)
            },
            error: function (e) {
                $('#InfoText').css('color', '#dc3545')
                $('#InfoText').text('Error')
            },
        })
    })
})